<?php
/**
 * OPEN 平台基类
 * User: dxk <1024114660@qq.com>
 * Date: 2022/4/7
 */
namespace App\Service\OpenApi\AppApi;

use App\Service\Core\Admin\Power\AdminUserPowerService;
use App\Service\ParamsService;

class OpenBaseApi
{
    protected $request = [];
    //用来记录操作人openid
    protected $operate_id = 0;
    protected $operate_by = '';
    protected $device_id = '';
    protected $login_params = [];
    //每页显示数据量
    protected $page_size = 20;
    //app_key
    protected $app_key;
    protected $token;
    protected $app_secret;
    protected $third_app_key = '';//是否三方APP登录的app_key

    public function __construct($data)
    {
        $this->request = $data['request'];
        //操作人ID
        $this->login_params = $data['login_params'];
        $this->operate_id = intval($data['operate_id']);
        $this->device_id = trim($data['device_id']);
        $this->operate_by = trim($data['operate_by']);
        $this->app_key = trim($data['app_key']);
        $this->app_secret = trim($data['app_secret']);
        $this->token = trim($data['token']);
        $this->third_app_key = trim($data['third_app_key']);
    }

    /**
     * 生成wapurl
     * @param string $url
     * @param array $param
     * @param null $secure
     * @return string
     */
    protected function wapUrl(string $url, array $param = [], $secure = null): string
    {
        $param['app_key'] = $this->app_key;
        $param['token'] = $this->token;
        $param['noncestr'] = easy_random(16);
        $param['sign'] = $this->makeSign(['token' => $param['token'], 'noncestr' => $param['noncestr'], 'app_key' => $param['app_key']]);
        return easy_url('openapi/app/' . $url, $param, $secure);
    }

    /**
     * 生成签名
     * @param $params
     * @return string
     */
    private function makeSign($params): string
    {
        ksort($params);
        $stringToBeSigned = '';
        foreach ($params as $k => $v) {
            if (!str_starts_with($v, "@")) {
                if (!is_array($v)) {
                    $v = stripslashes($v);
                }
                $stringToBeSigned .= "$k$v";
            }
        }
        unset($k, $v);
        return strtoupper(md5($this->app_secret . $stringToBeSigned . $this->app_secret));
    }

    /**
     * Retrieve an input item from the request.
     * @param string|null $key
     * @param array|string|null $default
     * @return array|\ArrayAccess|mixed
     */
    public function input(string $key = null, array|string $default = null): mixed
    {
        return \Arr::get($this->request, $key, $default);
    }
}
